﻿using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace Faser_VoteSys.Utils.Security
{
    public class MD5Helper
    {
        public static string ComputeHash(string input)
        {
            using var md5 = MD5.Create();
            byte[] inputBytes = Encoding.ASCII.GetBytes(input);
            byte[] hashBytes = md5.ComputeHash(inputBytes);

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            {
                sb.Append(hashBytes[i].ToString("X2"));
            }
            return sb.ToString();
        }

        public static string ComputeSaltedHash(string input, string salt)
        {
            return ComputeHash(input + salt);
        }

        public static string GenerateSalt(int length = 8)
        {
            const string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
            var random = new System.Random();
            var randomChar = Enumerable.Repeat(valid, length)
                .Select(s => s[random.Next(s.Length)])
                .ToArray();
            return new string(randomChar);
        }
    }
}
